﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;

namespace Goldlight.Mvvm.Base.Behaviors
{
    /// <summary>
    /// This behavior adds click capability to items that don't, intrinsically, support commands on a click such
    /// as a listitem.
    /// </summary>
    public class ClickBehavior
    {
        /// <summary>
        /// Dependency property to register the click command.
        /// </summary>
        public static DependencyProperty ClickCommandProperty =
            DependencyProperty.RegisterAttached("Click", typeof(ICommand), typeof(ClickBehavior),
            new FrameworkPropertyMetadata(null, new PropertyChangedCallback(ClickChanged)));

        /// <summary>
        /// Set the click command property.
        /// </summary>
        public static void SetClick(DependencyObject target, ICommand value)
        {
            target.SetValue(ClickCommandProperty, value);
        }

        /// <summary>
        /// Handle the click changed event.
        /// </summary>
        private static void ClickChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            UIElement element = target as UIElement;

            if (element != null)
            {
                if (e.NewValue != null && e.OldValue == null)
                {
                    element.MouseLeftButtonUp += new MouseButtonEventHandler(element_MouseLeftButtonUp);
                }
                else if (e.NewValue == null && e.OldValue != null)
                {
                    element.MouseLeftButtonUp -= new MouseButtonEventHandler(element_MouseLeftButtonUp);
                }
            }
        }

        static void element_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            UIElement element = sender as UIElement;

            if (element != null)
            {
                ICommand cmd = element.GetValue(ClickCommandProperty) as ICommand;
                cmd.Execute(null);
            }
        }
    }
}
